package com.valpha.obsutil;

import android.text.TextUtils;
import android.util.Log;

import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.DownloadFileRequest;
import com.obs.services.model.DownloadFileResult;
import com.obs.services.model.GetObjectRequest;
import com.obs.services.model.ObsObject;
import com.obs.services.model.ProgressListener;
import com.obs.services.model.ProgressStatus;
import com.obs.services.model.PutObjectResult;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

import kotlin.NotImplementedError;

public class OBS {

    private static final String TAG = OBS.class.getSimpleName();
    private static final String DEFAULT_BUCKET_NAME = "deepinandroid";
    private static final String DEFAULT_END_POINT = "https://obs.cn-east-2.myhuaweicloud.com";
    private static final String DEFAULT_AK = "HCSAQEK2ULXUZCFTXVTV";
    private static final String DEFAULT_SK = "xBE0GpcWrCHRCtSGZhFDyq3nC0pLKKbDaD5HU2IF";

    private static OBS sInstance;
    private ObsClient mObsClient;

    public static OBS getInstance() {
        if (sInstance == null) {
            synchronized (OBS.class) {
                if (sInstance == null) {
                    sInstance = new OBS();
                }
            }
        }
        return sInstance;
    }

    private OBS() {
        // 创建ObsClient实例
        mObsClient = new ObsClient(DEFAULT_AK, DEFAULT_SK, DEFAULT_END_POINT);
    }

    public void setObsClient(ObsClient obsClient) {
        mObsClient = obsClient;
    }

    public boolean uploadImage(File image, String key) {
        return uploadImage(image, DEFAULT_BUCKET_NAME, key);
    }

    public boolean uploadImage(File image, String bucket, String key) {
        if (image == null || !image.exists()) {
            Log.d(TAG, "Image does not exist");
            return false;
        }

        if (TextUtils.isEmpty(key)) {
            Log.d(TAG, "ImageName is empty");
            return false;
        }

        if (mObsClient == null) {
            Log.d(TAG, "ImageName is empty");
            return false;
        }

        try {
            PutObjectResult putObjectResult = mObsClient.putObject(bucket, key, image);
            Log.d(TAG, putObjectResult.toString());
        } catch (ObsException e) {
            Log.e(TAG, e.getMessage());
            return false;
        }
        return true;
    }

    public boolean downloadImageByStream(String key, String localFilePath, boolean isSetDownloadProgressListener) {
        return downloadImageByStream(DEFAULT_BUCKET_NAME, key, localFilePath, isSetDownloadProgressListener);
    }

    public boolean downloadImageByStream(String bucket, String key, String localFilePath, boolean isSetDownloadProgressListener) {
        if (mObsClient == null) {
            Log.d(TAG, "DownloadImageByStream failed : ImageName is empty");
            return false;
        }
        GetObjectRequest request = new GetObjectRequest(bucket, key);
        if (isSetDownloadProgressListener) {
            request.setProgressListener(new ProgressListener() {

                @Override
                public void progressChanged(ProgressStatus status) {
                    // 获取下载平均速率
                    Log.d(TAG, "AverageSpeed : " + status.getAverageSpeed());
                    // 获取下载进度百分比
                    Log.d(TAG,"TransferPercentage : " + status.getTransferPercentage());
                }
            });
            // 每下载0.5MB数据反馈下载进度
            request.setProgressInterval(512 * 1024L);
        }
        ObsObject obsObject = mObsClient.getObject(request);
        // 读取对象内容
        InputStream input = obsObject.getObjectContent();
        byte[] b = new byte[1024];
        int len;
        try {
            File localFile = new File(localFilePath);
            if (!localFile.exists()) {
                localFile.getParentFile().mkdirs();
                localFile.createNewFile();
            }
            FileOutputStream output = new FileOutputStream(localFilePath);
            while ((len = input.read(b)) != -1) {
                output.write(b, 0, len);
            }
            output.close();
            input.close();
        } catch (IOException e) {
            Log.e(TAG, "DownloadImageByStream failed : " + e.getMessage());
            return false;
        }
        return true;
    }


    public boolean downloadImage(String key, String localFilePath, boolean isSetDownloadProgressListener) {
        return downloadImage(DEFAULT_BUCKET_NAME, key, localFilePath, isSetDownloadProgressListener);
    }


    public boolean downloadImage(String bucket, String key, String localFilePath, boolean isSetDownloadProgressListener) {
        if (mObsClient == null) {
            Log.d(TAG, "DownloadImage failed : ImageName is empty");
            return false;
        }

        DownloadFileRequest request = new DownloadFileRequest(bucket, key);
        if (isSetDownloadProgressListener) {
            request.setProgressListener(new ProgressListener() {

                @Override
                public void progressChanged(ProgressStatus status) {
                    // 获取下载平均速率
                    Log.d(TAG, "AverageSpeed : " + status.getAverageSpeed());
                    // 获取下载进度百分比
                    Log.d(TAG,"TransferPercentage : " + status.getTransferPercentage());
                }
            });
            // 每下载0.5MB数据反馈下载进度
            request.setProgressInterval(512 * 1024L);
        }

        // 设置下载对象的本地文件路径
        request.setDownloadFile(localFilePath);
        // 设置分段下载时的最大并发数
        request.setTaskNum(5);
        // 设置分段大小为10MB
        request.setPartSize(1024 * 1024);
        // 开启断点续传模式
        request.setEnableCheckpoint(true);
        try {
            File localFile = new File(localFilePath);
            if (!localFile.exists()) {
                localFile.getParentFile().mkdirs();
                localFile.createNewFile();
            }
            // 进行断点续传下载
            DownloadFileResult result = mObsClient.downloadFile(request);
            Log.d(TAG, result.toString());
        } catch (Exception e) {
            // 发生异常时可再次调用断点续传下载接口进行重新下载
            Log.e(TAG, "DownloadImage failed : " + e.getMessage());
            return false;
        }
        return true;
    }

    public void closeObs() {
        if (mObsClient != null) {
            try {
                mObsClient.close();
            } catch (IOException e) {
                Log.d(TAG, e.getMessage());
            } finally {
                mObsClient = null;
            }
        }
    }
}
